package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * a10_复原IP地址复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/4/10
 */
public class a10_复原IP地址复习3 {
    public static void main(String[] args) {
        a10_复原IP地址复习3 test = new a10_复原IP地址复习3();
        test.restoreIpAddresses("0000");
    }

    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();
        LinkedList<String> path = new LinkedList<>();
        traversal(result, path, s.toCharArray(),0);
        return result;
    }

    private void traversal(List<String> result,
                           LinkedList<String> path,
                           char[] chars,
                           int startIdx){
        if(path.size() == 4){
            if(startIdx == chars.length){
                String collect = path.stream().collect(Collectors.joining("."));
                result.add(collect);
                return;
            }else {
                return;
            }
        }


        for (int i = startIdx; i < Math.min(startIdx + 3,chars.length); i++) {
            if (!check(chars, startIdx, i)) {
                continue;
            }
            path.add(split(chars, startIdx, i));
            traversal(result, path,chars,i+1);
            path.removeLast();
        }
    }

    private boolean check(char[] chars,int leftIdx,int rightIdx){
        if (rightIdx > leftIdx && chars[leftIdx] == '0') {
            return false;
        }

        StringBuilder sb = new StringBuilder();
        while (leftIdx <= rightIdx) {
            if((int)chars[leftIdx] < 48 || (int)chars[leftIdx] > 57){
                return false;
            }
            sb.append(chars[leftIdx]);
            leftIdx++;
        }

        String str = sb.toString();

        if(Integer.valueOf(str) > 255){
            return false;
        }

        return true;
    }

    private String split(char[] chars,int leftIdx,int rightIdx){
        StringBuilder sb = new StringBuilder();
        while (leftIdx <= rightIdx) {
            sb.append(chars[leftIdx]);
            leftIdx++;
        }
        return sb.toString();
    }



}
